package com.lank.gateway.swagger;

import lombok.AllArgsConstructor;
import org.springframework.cloud.gateway.route.RouteLocator;
import org.springframework.context.annotation.Primary;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Component;
import springfox.documentation.swagger.web.SwaggerResource;
import springfox.documentation.swagger.web.SwaggerResourcesProvider;

import java.util.ArrayList;
import java.util.List;

/**
 * @author 郑海宾
 * @since 2020/8/22 下午6:49 星期六
 */
@Component
@Primary
@AllArgsConstructor
@Profile({"dev", "check"})
public class SwaggerResourceProviderImpl implements SwaggerResourcesProvider {

    public static final String API_URI = "/v2/api-docs";
    private final RouteLocator routeLocator;

    @Override
    public List<SwaggerResource> get() {
        List<SwaggerResource> resources = new ArrayList<>();
        routeLocator.getRoutes().subscribe(route ->
                resources.add(
                        swaggerResource(
                                route.getId().substring("ReactiveCompositeDiscoveryClient_".length()),
                                route.getUri().getHost() + API_URI
                        )
                )
        );

        return resources;
    }

    /**
     * 把SwaggerInfo信息加载到SwaggerUI界面的方法
     *
     * @param name     资源名称
     * @param location 资源路径
     * @return 资源
     */
    private SwaggerResource swaggerResource(String name, String location) {
        SwaggerResource swaggerResource = new SwaggerResource();
        swaggerResource.setName(name);
        swaggerResource.setLocation(location);
        swaggerResource.setSwaggerVersion("2.0");
        return swaggerResource;
    }
}
